/* eslint-disable no-shadow */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable react-hooks/exhaustive-deps */
import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {
  Dimensions,
  KeyboardAvoidingView,
  TouchableWithoutFeedback,
} from 'react-native';
import {
  Text,
  View,
  Card,
  Colors,
  Checkbox,
  Button,
  Image,
} from 'react-native-ui-lib';
import Logo from 'components/Logo';
import Input from 'components/Input';
import AntdIcons from 'react-native-vector-icons/AntDesign';
import {useRequest} from 'ahooks';
import {post} from '@/utils/request';
import * as Animatable from 'react-native-animatable';
import Storage from '@/utils/storage';
import {getUserInfo} from '@/utils/service';

let {width, height} = Dimensions.get('window');
let reg_tel = /^\d{11}$/;

function Login(props) {
  let {navigation, appTheme, dispatch, statusbars} = props;
  const [username, setusername] = useState();
  const [password, setpassword] = useState();
  const [agree, setagree] = useState(true);
  const [status, setstatus] = useState(null);

  const {runAsync, loading} = useRequest(post, {
    manual: true,
    formatResult: res => res,
    onSuccess: async result => {
      if (result?.code === 0) {
        await Storage.set('token', result?.data?.data?.token);
        await getUserInfo(dispatch);
        navigation.reset({
          index: 0,
          routes: [{name: 'Homepage'}],
        });
      }
    },
  });

  let userprops = {
    placeholder: '用户名',
    value: username,
    lefticon: 'user',
    allowClear: true,
    onChange: val => {
      setusername(val);
      if (!val) {
        setstatus('empty');
        return;
      }
      // if (!reg_tel.test(val)) {
      //   setstatus('incorrect');
      //   return;
      // }
      setstatus(null);
    },
  };
  let pwdprops = {
    placeholder: '密码',
    value: password,
    lefticon: 'lock1',
    type: 'password',
    allowClear: true,
    onChange: val => {
      setpassword(val);
      if (!val) {
        setstatus('empty');
        return;
      }
      setstatus(null);
    },
  };

  return (
    <KeyboardAvoidingView
      behavior={'height'}
      style={{flex: 1}}
      keyboardVerticalOffset={-60}>
      <View
        flex-1
        center
        style={{backgroundColor: Colors.backgroundColor, position: 'relative'}}>
        <View style={{height: height / 2, paddingTop: 32}} center>
          <Logo status={status} appTheme={appTheme} />
          <TouchableWithoutFeedback
            onPress={() => {
              dispatch({
                type: 'CHANGE_THEME',
                appTheme: appTheme === 'light' ? 'dark' : 'light',
              });
            }}>
            <Image
              source={
                appTheme === 'light'
                  ? require('@/assets/tasks.png')
                  : require('@/assets/tasks_w.png')
              }
              width={74}
              height={18}
              cover={false}
              style={{marginTop: 20, marginBottom: 36}}
            />
          </TouchableWithoutFeedback>

          <Input {...userprops} />

          <View marginT-12>
            <Input {...pwdprops} />
          </View>

          <View
            height={66}
            row
            marginT-8
            width={width / 1.2}
            style={{overflow: 'hidden'}}
            padding-12>
            <Checkbox
              size={20}
              color={Colors.primaryColor}
              value={agree}
              onValueChange={agree => setagree(agree)}
            />
            <View marginL-8 flex-1>
              <Text numberOfLines={6} body>
                我已阅读并同意{' '}
                <Text color={Colors.primaryColor}>TASKS用户协议</Text> 和{' '}
                <Text color={Colors.primaryColor}>隐私政策</Text>
              </Text>
            </View>
          </View>
        </View>
        <View flex-1 centerH>
          <Card
            style={{
              width: 66,
              height: 66,
              backgroundColor:
                username && password && agree
                  ? Colors.primaryColor
                  : Colors.cardbackgroundColor,
            }}
            borderRadius={88}
            center
            onPress={async () => {
              if (agree) {
                setstatus('loading');

                await runAsync('/system/login', {
                  account: username,
                  password: password,
                });

                setTimeout(() => {
                  setstatus(null);
                }, 2000);
              }
            }}>
            {loading ? (
              <Animatable.View animation={'rotate'} iterationCount={6}>
                <AntdIcons
                  name="loading1"
                  size={24}
                  color={username && password ? Colors.white : '#999'}
                />
              </Animatable.View>
            ) : (
              <AntdIcons
                name="arrowright"
                size={24}
                color={username && password && agree ? Colors.white : '#999'}
              />
            )}
          </Card>
        </View>

        <View
          row
          spread
          style={{
            position: 'absolute',
            bottom: 0,
            width: '100%',
            padding: 24,
          }}>
          <View />

          <Button
            round
            backgroundColor={Colors.colorBgSecondary}
            onPress={() => {
              navigation.navigate('SignIn');
            }}>
            <AntdIcons
              name="adduser"
              size={24}
              style={{color: Colors.subheadingColor}}
            />
          </Button>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
}

const mapStateToProps = state => {
  return {
    appTheme: state.appTheme,
  };
};

export default connect(mapStateToProps)(Login);
